const path = require('path');
const BaseHandler = require(path.join(__dirname, '../libs/baseHandler.js'));
const handler = new BaseHandler();
const User = require('../models/users');
const Records = require('../models/record');
const mongoose = require('mongoose');
const dayjs = require('dayjs');

// 消费/收入每个分类总额
handler.analysisClassify = async function (ctx) {
  const { userIds, start, end, type } = ctx.request.body;

  const match = {};
  if (userIds) {
    match.user = {
      $in: userIds.map((i) => mongoose.Types.ObjectId(i)),
    };
  }
  if (start && end) {
    match.created = {
      $gte: dayjs(start).format('YYYY-MM-DD HH:mm:ss'),
      $lte: dayjs(end).format('YYYY-MM-DD HH:mm:ss'),
    };
  }

  const query = [
    {
      $match: { ...match },
    },
    {
      $lookup: {
        from: 'tags',
        localField: 'tag',
        foreignField: '_id',
        as: 'tags',
      },
    },
    { $unwind: `$tags` },
    {
      $project: {
        _id: '$tags._id',
        name: '$tags.name',
        isIncome: '$tags.isIncome',
        amount: 1,
      },
    },
    {
      $match: {
        isIncome: type === 'income',
      },
    },
    {
      $group: {
        _id: '$_id',
        name: { $first: '$name' },
        value: { $sum: '$amount' },
      },
    },
  ];

  const classify = await Records.aggregate([...query]);
  return handler.restSuccess(ctx, classify);
};

// 计算选定时间范围内每天日期的消费额
handler.analysisDate = async function (ctx) {
  const { userIds, type, start, end, range = 'day' } = ctx.request.body;

  const match = {};
  if (userIds) {
    match.user = {
      $in: userIds.map((i) => mongoose.Types.ObjectId(i)),
    };
  }

  if (start && end) {
    match.created = {
      $gte: dayjs(start).format('YYYY-MM-DD HH:mm:ss'),
      $lte: dayjs(end).format('YYYY-MM-DD HH:mm:ss'),
    };
  }

  const rangeMap = {
    day: 10,
    month: 7,
    year: 4,
  };

  const query = [
    {
      $match: { ...match },
    },
    {
      $lookup: {
        from: 'tags',
        localField: 'tag',
        foreignField: '_id',
        as: 'tags',
      },
    },
    { $unwind: `$tags` },
    {
      $project: {
        _id: { $substr: ['$created', 0, rangeMap[range]] },
        isIncome: '$tags.isIncome',
        amount: 1,
      },
    },
    {
      $match: {
        isIncome: type === 'income',
      },
    },
    {
      $group: {
        _id: '$_id',
        value: { $sum: '$amount' },
      },
    },
    {
      $sort: { _id: -1 },
    },
  ];

  const date = await Records.aggregate([...query]);
  return handler.restSuccess(ctx, date);
};

module.exports = handler;
